//
//  HNDoctorListViewController.m
//  JHFBaseProject
//
//  Created by 朱传正 on 2016/12/14.
//  Copyright © 2016年 好牛. All rights reserved.
//

#import "HNDoctorListViewController.h"
#import "HNDoctorDetailViewController.h"

@interface HNDoctorListViewController ()

//选项卡形态控制
@property (nonatomic,strong)UILabel *choiceLabel0;
@property (nonatomic,strong)UIView *choiceLineView0;
@property (nonatomic,strong)UILabel *choiceLabel1;
@property (nonatomic,strong)UIView *choiceLineView1;
@property (nonatomic,strong)UILabel *choiceLabel2;
@property (nonatomic,strong)UIView *choiceLineView2;

@property (nonatomic,strong)UIScrollView *selectSectionView;//选择View

@property (nonatomic,assign)NSInteger choiceBtnTag;

@property (nonatomic,assign)CGFloat contentHeight;

@property (nonatomic,strong)NSMutableArray *docterListSource;

@property (nonatomic,assign)NSInteger docterListCount;

@property (nonatomic,assign) NSUInteger cur;//当前
@property (nonatomic,assign) CGFloat currentTag;


@property (nonatomic,strong) NSString *departmentId;
@property (nonatomic,strong) NSString *byHot;
@property (nonatomic,strong) NSString *byPrice;

@property (nonatomic,strong) NSArray *departmentArr;

@end

@implementation HNDoctorListViewController

-(UIScrollView *)selectSectionView{
    if (!_selectSectionView) {
        _selectSectionView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 40, kScreen_Width, kScreen_Height-40)];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideView)];
        _selectSectionView.backgroundColor = RGBA(255, 255, 255, 0);
        [_selectSectionView addGestureRecognizer:tap];
    }
    return _selectSectionView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self drawView];
    [self initData];
    
}

-(void)drawView{
    
    _byHot = nil;
    _byPrice = nil;
    _departmentId = nil;
    
    //设置头部快
    [self setHeadSection];
    //设置医生列表
    _doctorListScrollView.bounces = YES;
    _doctorListScrollView.backgroundColor = RGB(236, 240, 241);
    
    [self setDoctorList];
    //设置弹出View
    [self setPopSelectView:nil];
    
    _doctorListScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 40, kScreen_Width, kScreen_Height-70 - 40)];
    _doctorListScrollView.bounces = YES;
    
    [self.view addSubview:_doctorListScrollView];
    
    //设置医生列表
    _doctorListScrollView.backgroundColor = RGB(236, 240, 241);
    
    _shoppingView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 0)];
    [_doctorListScrollView addSubview:_shoppingView];
    
    
    [self setDoctorList];
    
    UILabel *lineLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, 0.5)];
    lineLabel.backgroundColor = [UIColor grayColor];
    [self.view addSubview:lineLabel];
    
}

-(void)setHeadSection{
    
    _headSectionView.backgroundColor = [UIColor whiteColor];
    NSArray *nameArray = [NSArray arrayWithObjects:@"筛选",@"高人气",@"低价格",nil];
    
    for (int i = 0; i < nameArray.count; i++) {
        UIView *itemView = [[UIView alloc]initWithFrame:CGRectMake( kScreen_Width/3 * i, 0, kScreen_Width/3,_headSectionView.frame.size.height)];
        [self.headSectionView addSubview:itemView];
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, itemView.frame.size.width, itemView.frame.size.height - 20)];
        label.tag = 100 + i;
        label.text = nameArray[i];
        label.textColor = RGB(112, 112, 112);
        label.textAlignment =  NSTextAlignmentCenter ;
        label.font = [UIFont systemFontOfSize:14];
        [itemView addSubview:label];
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(5, itemView.frame.size.height - 1, itemView.frame.size.width-10,1)];
        lineView.tag = 500 + i;
        [lineView setHidden:YES];
        lineView.backgroundColor = RGB(85, 206, 84);
        [itemView addSubview:lineView];
        switch (i) {
            case 0:
                self.choiceLabel0 = label;
                self.choiceLineView0 = lineView;
                break;
            case 1:
                self.choiceLabel1 = label;
                self.choiceLineView1 = lineView;
                break;
            case 2:
                self.choiceLabel2 = label;
                self.choiceLineView2 = lineView;
                break;
                
            default:
                break;
        }
        //添加点击按钮 - 切换
        UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [clickBtn setTitle:@"" forState:UIControlStateNormal];
        [clickBtn setBackgroundColor:RGBA(255, 255, 255, 0)];
        [clickBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        clickBtn.frame = CGRectMake(0, 0, itemView.frame.size.width, itemView.frame.size.height);//大小和位置
        clickBtn.tag = 500 + i;
        [clickBtn addTarget:self action:@selector(clickInAction:) forControlEvents:UIControlEventTouchUpInside];//button被按下又抬起后发生的事件
        [itemView addSubview:clickBtn];
    }
    
}


//推荐、闲置、寄卖、代购选择后执行的方法
-(void)clickInAction:(UIButton *)btn{
    
    switch (btn.tag - 500) {
        case 0://推荐
            [self setStateColor:0];
            break;
        case 1://关注
            [self setStateColor:1];
            [self getDoctorMessage:btn];
            //            [self clickInAction:currentBtn];//保证会退回来有数据
            
            break;
        case 2://闲置
            [self getDoctorMessage:btn];
            [self setStateColor:2];
            //            [self getGoodsDate:@"1"];
            break;
        default:
            break;
    }
}

//选择按钮状态变换
-(void)setStateColor:(NSInteger)num{
    switch (num) {
        case 0://推荐
            self.choiceLabel0.textColor = RGB(85, 206, 84);
            [self.choiceLineView0 setHidden:NO];
            self.choiceLabel1.textColor = RGBJ(77);
            [self.choiceLineView1 setHidden:YES];
            self.choiceLabel2.textColor = RGBJ(77);
            [self.choiceLineView2 setHidden:YES];
            
            [self.selectSectionView setHidden:NO];
            
            break;
        case 1://关注
            self.choiceLabel0.textColor = RGBJ(77);
            [self.choiceLineView0 setHidden:YES];
            self.choiceLabel1.textColor = RGB(85, 206, 84);
            [self.choiceLineView1 setHidden:NO];
            self.choiceLabel2.textColor = RGBJ(77);
            [self.choiceLineView2 setHidden:YES];
            
            [self.selectSectionView setHidden:YES];
            break;
        case 2://闲置
            self.choiceLabel0.textColor = RGBJ(77);
            [self.choiceLineView0 setHidden:YES];
            self.choiceLabel1.textColor = RGBJ(77);
            [self.choiceLineView1 setHidden:YES];
            self.choiceLabel2.textColor = RGB(85, 206, 84);
            [self.choiceLineView2 setHidden:NO];
            
            [self.selectSectionView setHidden:YES];
            
            break;
            
        default:
            break;
    }
    
}

#pragma mark - 弹出的选择View
-(void)setPopSelectView:(NSArray *)arr{
//    NSArray *nameArr = [NSArray arrayWithObjects:@"头部",@"身体",@"脚部", nil];
    
    NSArray *departmentArr =  [Util getDepartmentArr];
    _departmentArr = departmentArr;
    NSLog(@"%@",departmentArr);
    
    float popSelectViewHeight = 0;
    for (int i = 0; i<departmentArr.count; i++) {
        //添加点击按钮---添加一个按钮
        UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        NSString *name = [NSString stringWithFormat:@"%@",[departmentArr[i] objectForKey:@"name"]];
        [clickBtn setTitle:name forState:UIControlStateNormal];
        [clickBtn setFont:[UIFont systemFontOfSize:15]];
        [clickBtn setBackgroundColor:[UIColor whiteColor]];
        [clickBtn setTitleColor:RGBJ(29) forState:UIControlStateNormal];
        clickBtn.tag = 1000 + i;
        clickBtn.frame = CGRectMake(0,35*i, kScreen_Width/3, 35);
        [clickBtn addTarget:self action:@selector(getDoctorMessage:) forControlEvents:UIControlEventTouchUpInside];
        [self.selectSectionView addSubview:clickBtn];
        
        popSelectViewHeight = popSelectViewHeight + 35;
    }
    
    if (popSelectViewHeight > _selectSectionView.frame.size.height) {
        _selectSectionView.contentSize = CGSizeMake(_selectSectionView.frame.size.width, popSelectViewHeight);
    }
    
    [self.view addSubview:self.selectSectionView];
    [self.view bringSubviewToFront:self.selectSectionView];
    [self.selectSectionView setHidden:YES];
}

-(void)hideView{
    [self.selectSectionView setHidden:YES];
}

#pragma mark - 设置列表
-(void)setDoctorList{
    CGFloat bl = 6;//border边距
    CGFloat gl = 4;//gap间隙
    
    NSInteger num = self.docterListSource.count;
    
    NSLog(@"------------self.docterListSource = %@",self.docterListSource);
    
    //当商品列表为空时
    
    for (NSInteger i = 0; i < self.docterListSource.count; i++) {
        
        NSDictionary *goodsDataDic  = self.docterListSource[i];
        UIView *itemView = [[UIView alloc]initWithFrame:CGRectMake((kScreen_Width/2 - bl/2) * !(i%2 == 0) + bl, _contentHeight, kScreen_Width/2, 0)];
        [self.shoppingView addSubview:itemView];
        //商品图
        UIImageView *goodsImageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, gl * 2, kScreen_Width/2 - bl*3/2, kScreen_Width/2 - bl*3/2)];
        
        NSString *goodsImageStr = [NSString stringWithFormat:@"%@%@",url_Base,[goodsDataDic objectForKey:@"photo"]];
        [goodsImageView sd_setImageWithURL:[NSURL URLWithString:goodsImageStr] placeholderImage:[UIImage imageNamed:@"D99GN4P63Q4F@2x.png"]];
        
        goodsImageView.layer.masksToBounds = YES;
        
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        maskLayer.path = [UIBezierPath bezierPathWithRoundedRect:goodsImageView.bounds  byRoundingCorners: UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii: (CGSize){5.0f, 5.0f}].CGPath;
        goodsImageView.layer.mask = maskLayer;
        
        [itemView addSubview:goodsImageView];
        
        //商品名
        UILabel *nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, goodsImageView.frame.origin.y + goodsImageView.frame.size.height, goodsImageView.frame.size.width, 18 + gl)];
        nameLabel.numberOfLines = 1;
        nameLabel.backgroundColor = [UIColor whiteColor];
        nameLabel.font = [UIFont systemFontOfSize:15];
        nameLabel.textColor = RGBJ(165);
        NSString *realName = [NSString stringWithFormat:@"%@",[goodsDataDic objectForKey:@"realName"]];
        NSString *nickname = [NSString stringWithFormat:@"%@",[goodsDataDic objectForKey:@"nickname"]];
        NSString *username = [NSString stringWithFormat:@"%@",[goodsDataDic objectForKey:@"username"]];
        if ([AppConfig isNULL:nickname]) {
            if ([AppConfig isNULL:realName]){
                nameLabel.text = username;
            }else{
                nameLabel.text = realName;
            }
        }else {
            nameLabel.text = nickname;
        }
        [itemView addSubview:nameLabel];
        //商品描述
        UILabel *detailLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, nameLabel.frame.origin.y + nameLabel.frame.size.height, goodsImageView.frame.size.width, 15 + gl)];
        detailLabel.backgroundColor = [UIColor whiteColor];
        detailLabel.numberOfLines = 1;
        detailLabel.font = [UIFont systemFontOfSize:11];
        detailLabel.textColor = RGB(112, 112, 112);
        
        detailLabel.text = [NSString stringWithFormat:@" %@",[goodsDataDic objectForKey:@"flag1"]];
        [itemView addSubview:detailLabel];
        
        
        UIView *gapView = [[UIView alloc]initWithFrame:CGRectMake(0, detailLabel.frame.origin.y + detailLabel.frame.size.height, goodsImageView.frame.size.width, 10)];
        
        gapView.layer.masksToBounds = YES;
        
        CAShapeLayer *gapViewLayer = [CAShapeLayer layer];
        gapViewLayer.path = [UIBezierPath bezierPathWithRoundedRect:detailLabel.bounds  byRoundingCorners: UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii: (CGSize){5.0f, 5.0f}].CGPath;
        detailLabel.layer.mask = gapViewLayer;
        
        [itemView addSubview:detailLabel];
        
        //添加点击按钮
        UIButton *clickBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [clickBtn setTitle:@"" forState:UIControlStateNormal];
        [clickBtn setBackgroundColor:RGBA(255, 255, 255, 0)];
        [clickBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        clickBtn.tag = i + 10000;
        clickBtn.frame = goodsImageView.frame;
        [clickBtn addTarget:self action:@selector(enterDoctorDetail:) forControlEvents:UIControlEventTouchUpInside];
        [itemView addSubview:clickBtn];
        
        //设置列表高度
        CGRect itemViewFrame = itemView.frame;
        itemViewFrame.size.height = goodsImageView.frame.size.height + detailLabel.frame.size.height + nameLabel.frame.size.height + gapView.frame.size.height ;
        itemView.frame = itemViewFrame;
        if (i%2 == 1 || (i + 1 == num && num%2 == 1)) {
            //设置列表高度
            _contentHeight = _contentHeight + itemView.frame.size.height;
            //最后一行加载后再改变scrollView高度
            if(i + 1 == num){
                _doctorListScrollView.contentSize = CGSizeMake(kScreen_Width, _contentHeight);
            }
            //设置商品高度
            CGRect shoppingViewFrame = self.shoppingView.frame;
            shoppingViewFrame.size.height = shoppingViewFrame.size.height + itemView.frame.size.height;
            self.shoppingView.frame = shoppingViewFrame;
        }
    }
    
    
    self.docterListCount = self.docterListSource.count;
}

#pragma -mark 进入医生详情页
-(void)enterDoctorDetail:(UIButton *)btn{
    NSInteger tag = btn.tag - 10000;
    NSDictionary *dic = _docterListSource[tag];
    NSString *userId = [NSString stringWithFormat:@"%@",[dic objectForKey:@"userId"]];
    
    HNDoctorDetailViewController *doctorDetailVC = [[HNDoctorDetailViewController alloc]init];
    doctorDetailVC.title = @"医生详情";
    doctorDetailVC.userId = userId;
    [self.navigationController pushViewController:doctorDetailVC animated:YES];
}

-(void)initData{
    self.docterListSource = [[NSMutableArray alloc]init];
    
    [self getDoctorMessage:nil];
}


#pragma mark - 获取列表数据
-(void)getDoctorMessage:(UIButton *)btn{
   [self.selectSectionView setHidden:YES];
    _docterListSource = [[NSMutableArray alloc]init];
    _docterListCount = 0;
    
    
    NSInteger tag = btn.tag;
    _currentTag = tag;
    
    //高人气  tag = 501 低价格  tag = 502
    //筛选是 1000 ...

    if (tag == 501) {
        if ([AppConfig isNULL:_byHot]) {
            _byHot = @"1";
//             _byPrice = @"";
        }else{
            _byPrice = @"";
            if ([_byHot isEqualToString:@"1"]) {
                _choiceLabel1.text = @"低人气";
              
                _byHot = @"0";
            }else{
                _choiceLabel1.text = @"高人气";
              
                _byHot = @"1";
            }
        }
    }else if (tag == 502){
        if ([AppConfig isNULL:_byPrice]) {
            _byPrice = @"1";
//            _byHot = @"";
        }else{
            
            if ([_byPrice isEqualToString:@"1"]) {
                _choiceLabel2.text = @"高价格";
                
                _byPrice = @"0";
            }else{
                _choiceLabel2.text = @"低价格";
                
                _byPrice = @"1";
            }
        }

        
    }else if (tag >= 1000){
        
    }
    
    NSMutableDictionary *param = [NSMutableDictionary dictionaryWithObjectsAndKeys:static_sessionId,@"sessionId",nil];
    [param setObject:[NSString stringWithFormat:@"%ld",_cur] forKey:@"cur"];
     [param setObject:@"1" forKey:@"isDoctor"];
    if (!([AppConfig isNULL:_departmentId] || [_departmentId isEqualToString:@""])) {
         [param setObject:_departmentId forKey:@"departmentId"];
    }
    if (!([AppConfig isNULL:_byHot] || [_byHot isEqualToString:@""])) {
            [param setObject:_byHot forKey:@"byHot"];
    }
    if (!([AppConfig isNULL:_byPrice] || [_byPrice isEqualToString:@""])) {
        [param setObject:_byPrice forKey:@"byPrice"];
    }

    if (![AppConfig isNULL:_keyword]) {
        [param setObject:_keyword forKey:@"keyword"];
    }
    
    NSLog(@"param = %@",param);
    
    
    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:url_doctor_list parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError * error;
        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
        [self hideHud];
        if (error) {
            NSLog(@"====error1:%@",error);
            [self showHint:@"获取医生列表失败"];
            NSLog(@"==dict:%@",data);
            return;
        }
        NSLog(@"==dict:%@",data);
        
        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
        if ([result isEqualToString:@"1"]) {
            NSArray * obj = [NSArray arrayWithArray:[data objectForKey:@"obj"]];
            NSLog(@"------obj = %@",obj);
            
            for (int i = 0; i < obj.count; i ++) {
                NSLog(@"%@",obj[i]);
                [self.docterListSource addObject:obj[i]];
            }
            
            NSLog(@"===self.docterListSource = %@",self.docterListSource);
            
            
            
            [_shoppingView removeFromSuperview];
            
            _doctorListScrollView.contentOffset = CGPointMake(0, 40);
            _contentHeight = 0;
            _shoppingView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, kScreen_Height-50)];
            [self.doctorListScrollView addSubview:_shoppingView];
            
            [self.view bringSubviewToFront:_selectSectionView];
            
            [self setDoctorList];
            
            
            
            
            
        }else{
            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
            if ([info isEqualToString:msg_InvalidLoginInformation]) {
                
                [AppConfig removeUserInfo];
                
                [[EMClient sharedClient] logout:YES];
                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_LOGINCHANGE object:@NO];
                
                LoginViewController *loginVC = [[LoginViewController alloc]init];
                
                [self.navigationController pushViewController:loginVC animated:YES];
            }
            [self showHint:info];
            [_doctorListScrollView.mj_footer endRefreshing];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
        NSLog(@"====error:%@",error);
        [self hideHud];
        [self showHint:@"获取医生列表失败"];
        [_doctorListScrollView.mj_footer endRefreshing];
    }];
}


//-(void)getMoreDoctorMessage{
//    self.cur ++;
//
//    
//    NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld",self.cur],@"cur",nil];
//    NSLog(@"param = %@",param);
//    
//    
//    AFHTTPSessionManager *manager = [[AFHTTPSessionManager manager] initWithBaseURL:[NSURL URLWithString:url_Base]];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    [manager POST:url_doctor_list parameters:param progress:^(NSProgress * _Nonnull downloadProgress) {
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSError * error;
//        NSDictionary * data=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:&error];
//        [self hideHud];
//        if (error) {
//            NSLog(@"====error1:%@",error);
//            [self showHint:@"获取医生列表失败"];
//            NSLog(@"==dict:%@",data);
//            return;
//        }
//        NSLog(@"==dict:%@",data);
//        
//        NSString * result = [NSString stringWithFormat:@"%@",[data objectForKey:@"result"]];
//        if ([result isEqualToString:@"1"]) {
//            NSArray * obj = [NSArray arrayWithArray:[data objectForKey:@"obj"]];
//            NSLog(@"------obj = %@",obj);
//            
//            for (int i = 0; i < obj.count; i ++) {
//                NSLog(@"%@",obj[i]);
//                [self.docterListSource addObject:obj[i]];
//            }
//            
//            NSLog(@"===self.docterListSource = %@",self.docterListSource);
//            
//            [_doctorListScrollView.mj_footer endRefreshing];
//        
//            
//            [self setDoctorList];
//            
//            
//            
//            
//        }else{
//            NSString * info = [NSString stringWithFormat:@"%@",[data objectForKey:@"msg"]];
//            [self showHint:info];
//            [_doctorListScrollView.mj_footer endRefreshing];
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull  error) {
//        NSLog(@"====error:%@",error);
//        [self hideHud];
//        [self showHint:@"获取医生列表失败"];
//        [_doctorListScrollView.mj_footer endRefreshing];
//    }];
//    
//    
//}



@end
